package com.zz.framework.core.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import java.io.IOException

/**
 * Copyright © 2023 stariverpan All rights reserved.
 * 2023/6/17 10:40.
 *
 * @version: V1.0
 */
class AudioPlayerUtils private constructor() {

    private var mediaPlayer: MediaPlayer? = null

    companion object {
        // -1: 初始状态，0: 播放完毕，1: 播放中
        var playStatus = -1
        private var instance: AudioPlayerUtils? = null
        fun newInstance(): AudioPlayerUtils {
            if (instance == null) {
                instance = AudioPlayerUtils()
            }
            return instance!!
        }
    }

    fun isPlaying(): Boolean  = playStatus == 1

    /**
     * **初始化 MediaPlayer**
     */
    private fun initMediaPlayer() {
        mediaPlayer?.release() // 释放旧的 MediaPlayer
        mediaPlayer = MediaPlayer().apply {
            setOnPreparedListener {
                it.start()
                playStatus = 1

                /**切换到扬声器并调整音量**/
                DeviceUtils.forceSpeakerOn()
                DeviceUtils.setMaxVolume()
            }
            setOnCompletionListener {
                DeviceUtils.forceHeadsetOn()
                playStatus = 0
            }
        }
    }

    /**
     * **播放 Assets 目录下的音频**
     */
    fun playAudioFromAssets(fileName: String,isLooping : Boolean = true) {
        val context = AppGlobals.getApplication()
        val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        try {
            initMediaPlayer() // 确保 MediaPlayer 被正确初始化
            // **加载 Assets 目录下的音频**
            val assetFileDescriptor = context.assets.openFd(fileName)
            mediaPlayer?.apply {
                setDataSource(
                    assetFileDescriptor.fileDescriptor,
                    assetFileDescriptor.startOffset,
                    assetFileDescriptor.length
                )
                assetFileDescriptor.close()
                /**设置音频流类型（兼容 API 26+）**/
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    setAudioAttributes(
                        AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_MEDIA)
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build()
                    )
                } else {
                    setAudioStreamType(AudioManager.STREAM_MUSIC)
                }
                this.isLooping = isLooping // 设置循环播放
                prepareAsync()   // 异步准备播放
            }

        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun playAudioByUrl(url: String) {
        try {
            initMediaPlayer() // 确保 MediaPlayer 被正确初始化
            mediaPlayer?.apply {
                setDataSource(url)
                /**设置音频流类型（兼容 API 26+）**/
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    setAudioAttributes(
                        AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_MEDIA)
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build()
                    )
                } else {
                    setAudioStreamType(AudioManager.STREAM_MUSIC)
                }
                isLooping = false // 设置循环播放
                prepareAsync()   // 异步准备播放
            }

        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * **停止播放**
     */
    fun stop() {
        mediaPlayer?.apply {
            stop()
            release()
        }
        mediaPlayer = null
        playStatus = 0
    }
}